package com.ruoyi.biz.imported.strategy;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.ruoyi.biz.imported.vo.ReqVO;
import com.ruoyi.biz.letter.domain.BizProvinceLetter;
import com.ruoyi.biz.letter.mapper.BizProvinceLetterMapper;
import com.ruoyi.biz.plan.domain.BizPlanConfig;
import com.ruoyi.biz.plan.mapper.BizPlanConfigMapper;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.poi.ExcelUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author Fei.Cong
 * @date 2024-07-17 14:32
 */
@Slf4j
@Service
public class ProvinceRegisterStrategy implements ImportedStrategy {

    @Autowired
    private BizProvinceLetterMapper bizProvinceLetterMapper;

    @SneakyThrows
    @Override
    public String importHandleData(ReqVO reqVO) {

        ExcelUtil<BizProvinceLetter> util = new ExcelUtil<BizProvinceLetter>(BizProvinceLetter.class);
//        Validator.validateNotEmpty(reqVO.getBillMonth(), "请选择月份");
        List<BizProvinceLetter> citySheet1List = util.importEasyExcel(reqVO.getFile().getInputStream(), 0, 1);

        if (CollectionUtil.isEmpty(citySheet1List)) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int existNum = 0;
        StringBuilder msg = new StringBuilder();

        if (!reqVO.isUpdateSupport()) {
            List<BizProvinceLetter> letterList = Lists.newArrayList();
            List<Long> ids = Lists.newArrayList();
            for (BizProvinceLetter cityLetter : citySheet1List) {
                try {
                    BizProvinceLetter entity = bizProvinceLetterMapper.selectOne(new LambdaQueryWrapper<BizProvinceLetter>()
                            .eq(BizProvinceLetter::getLetterNumber, cityLetter.getLetterNumber()));
                    if (Objects.nonNull(entity)) {
                        ids.add(entity.getId());
                        existNum++;
                        msg.append("<br/>" + existNum + "、信访件编号 " + cityLetter.getLetterNumber() + " <font color='blue'>已更新</font>");
                    } else {
                        successNum++;
                        msg.append("<br/>" + successNum + "、信访件编号 " + cityLetter.getLetterNumber() + " <font color='green'>已导入</font>");
                    }
                    cityLetter.setBillMonth(reqVO.getBillMonth());
                    cityLetter.setPCategoryId(Optional.ofNullable(cityLetter.getFirstCategoryName()).map(Long::new).orElse(null));
                    cityLetter.setSCategoryId(Optional.ofNullable(cityLetter.getSecondCategoryName()).map(Long::new).orElse(null));
                    letterList.add(cityLetter);
                } catch (Exception e) {
                    failureNum++;
                    String emsg = "<br/>" + failureNum + "、信访件编号 " + cityLetter.getLetterNumber() + " 导入失败：";
                    msg.append(emsg + e.getMessage());
                    log.error(emsg, e);
                }
            }
            if (CollectionUtil.isNotEmpty(ids)) {
                bizProvinceLetterMapper.deleteByIds(ids);
            }
            bizProvinceLetterMapper.insert(letterList);
        }

        msg.insert(0, "操作成功！成功 " + successNum + " 条，更新 " + existNum + " 条，失败 " + failureNum + " 条，数据如下：");

        return msg.toString();
    }
}
